<template>
  <div class="products">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入商品名称" 
            clearable 
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select 
            v-model="searchForm.type" 
            placeholder="请选择商品分类" 
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择状态" 
            clearable
            @change="handleSearch"
          >
            <el-option label="上架" value="ON_SALE" />
            <el-option label="下架" value="OFF_SALE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">添加商品</el-button>
      </div>
    </div>

    <!-- 商品列表 -->
    <el-table
      v-loading="loading"
      :data="productList"
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="商品图片" width="100">
        <template #default="{ row }">
          <el-image
            :src="getImageUrl(row.imageUrl)"
            :preview-src-list="[getImageUrl(row.imageUrl)]"
            fit="cover"
            class="product-image"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" min-width="200" show-overflow-tooltip />
      <el-table-column prop="type" label="商品分类" width="120">
        <template #default="{ row }">
          {{ getCategoryName(row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="100">
        <template #default="{ row }">
          ¥{{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="sales" label="销量" width="100" />
      <el-table-column prop="recommended" label="推荐" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.recommended"
            @change="handleToggleRecommended(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'ON_SALE' ? 'success' : 'info'">
            {{ row.status === 'ON_SALE' ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button
            type="primary"
            link
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 'ON_SALE' ? '下架' : '上架' }}
          </el-button>
          <el-button
            type="danger"
            link
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="type">
          <el-select v-model="form.type" placeholder="请选择商品分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrl">
          <el-upload
            class="product-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            accept="image/*"
          >
            <img v-if="form.imageUrl" :src="getImageUrl(form.imageUrl)" class="uploaded-image" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="form.price"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number
            v-model="form.stock"
            :min="0"
            :precision="0"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="推荐状态" prop="recommended">
          <el-switch v-model="form.recommended" />
        </el-form-item>
        <el-form-item label="商品积分" prop="productPoints">
          <el-input-number
            v-model="form.productPoints"
            :min="0"
            :precision="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import defaultProductImage from '@/assets/images/default-product.jpg'
import {
  getProductList,
  getCategories,
  addProduct,
  updateProduct,
  deleteProduct,
  toggleProductStatus,
  toggleProductRecommended
} from '@/api/admin'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 商品列表数据
const loading = ref(false)
const productList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 商品分类
const categories = ref([
  { id: 'ELECTRONICS', name: '电子产品' },
  { id: 'CLOTHING', name: '服装' },
  { id: 'FOOD', name: '食品' },
  { id: 'BOOKS', name: '图书' },
  { id: 'HOME', name: '家居' },
  { id: 'SPORTS', name: '运动' },
  { id: 'BEAUTY', name: '美妆' },
  { id: 'OTHER', name: '其他' }
])

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  type: '',
  imageUrl: '',
  price: 0,
  stock: 0,
  description: '',
  recommended: false,
  productPoints: 0,
  status: 'ON_SALE'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  imageUrl: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ],
  productPoints: [
    { required: true, message: '请输入商品积分', trigger: 'blur' },
    { type: 'number', min: 0, message: '积分必须大于等于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择商品状态', trigger: 'change' },
    { type: 'string', enum: ['ON_SALE', 'OFF_SALE'], message: '状态值无效', trigger: 'change' }
  ]
}

// 上传相关
const uploadUrl = 'http://localhost:8080/api/upload'
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 加载商品列表
const loadProductList = async () => {
  loading.value = true
  try {
    const res = await getProductList({
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    })
    if (res.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '加载商品列表失败')
    }
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 加载商品分类
const loadCategories = async () => {
  try {
    const res = await getCategories()
    if (res.code === 200 && res.data) {
      // 使用后端返回的分类数据，如果没有则使用默认分类
      categories.value = res.data.length > 0 ? res.data.map(item => ({
        id: item.id || item.type,
        name: item.name || item.displayName || item.type
      })) : categories.value
    } else {
      ElMessage.error(res.message || '加载商品分类失败')
    }
  } catch (error) {
    console.error('加载商品分类失败:', error)
    ElMessage.error('加载商品分类失败，请检查网络连接')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadProductList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadProductList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadProductList()
}

// 添加商品
const handleAdd = () => {
  dialogType.value = 'add'
  // 重置表单，确保数字字段初始化为0，状态字段初始化为ON_SALE
  form.id = ''
  form.name = ''
  form.type = ''
  form.imageUrl = ''
  form.price = 0
  form.stock = 0
  form.description = ''
  form.recommended = false
  form.productPoints = 0
  form.status = 'ON_SALE'  // 确保使用正确的枚举值
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addProduct(form)
          ElMessage.success('添加成功')
        } else {
          await updateProduct(form.id, form)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadProductList()
      } catch (error) {
        console.error(error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 切换商品状态
const handleToggleStatus = (row) => {
  const action = row.status === 'ON_SALE' ? '下架' : '上架'
  ElMessageBox.confirm(
    `确定要${action}该商品吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await toggleProductStatus(row.id)
      ElMessage.success(`${action}成功`)
      loadProductList()
    } catch (error) {
      console.error(error)
      ElMessage.error(`${action}失败`)
    }
  }).catch(() => {})
}

// 切换商品推荐状态
const handleToggleRecommended = (row) => {
  const action = row.recommended ? '推荐' : '取消推荐'
  ElMessageBox.confirm(
    `确定要${action}该商品吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await toggleProductRecommended(row.id, row.recommended)
      ElMessage.success(`${action}成功`)
      loadProductList()
    } catch (error) {
      console.error(error)
      ElMessage.error(`${action}失败`)
    }
  }).catch(() => {})
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该商品吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteProduct(row.id)
      ElMessage.success('删除成功')
      loadProductList()
    } catch (error) {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 上传相关方法
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    // 直接使用返回的URL
    form.imageUrl = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}

const handleUploadError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败，请重试')
}

// 工具函数
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

// 处理图片URL
const getImageUrl = (url) => {
  if (!url) return defaultProductImage
  return url
}

// 获取分类名称
const getCategoryName = (type) => {
  const category = categories.value.find(c => c.id === type)
  return category ? category.name : type
}

onMounted(() => {
  loadProductList()
  loadCategories()
})
</script>

<style scoped>
.products {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.operation-buttons {
  margin-left: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.product-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-uploader:hover {
  border-color: #409eff;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style> 